<?php

namespace app\data\command;

use app\data\model\DataWechat;
use app\data\model\DataUserTransfer;
use app\data\model\ShopOrder;
use think\admin\Command;
use think\admin\Exception;
use think\console\Input;
use think\console\Output;
use think\Model;

/**
 * 渠道佣金七号自动结算
 * Class ChannelSettleAccounts
 * @package app\data\command
 */
class ChannelSettleAccounts extends Command
{
    //已取消
    protected function configure()
    {
        $this->setName('xdata:ChannelSettleAccounts');
        $this->setDescription('渠道佣金七号自动结算');
    }

    /**
     * 业务指令执行
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $this->_autoSettleAccounts();
    }
    /**
     * 默认7号自动结算
     * @throws Exception
     */
    private function _autoSettleAccounts()
    {
        try {
            $length_time = sysconf('channel_can_jiesuantime');
            if(!isset($length_time)) $length_time = 7;
            $date = date('d');
            if($date != $length_time) return true;
            //获取未结算佣金记录  更改状态与佣金
            $map = [['status', '=',0]];
            $lists = DataWechat::lists($map,'id',array(
                'id'    =>'asc'
            ));
            if(empty($lists)) return true;
            $opera = [];
            $start_time = \Tools::getDateTimeByTime(strtotime("-1 months"),'Y-m').'-01 00:00:01';
            $end_time = \Tools::getDateTimeByTime(time(),'Y-m').'-01 00:00:01';
            $userDataWechatModel = new \app\data\model\DataWechat();
            $userDataWechatModel->startTrans();
            foreach($lists as &$v){
                $payment_amount = ShopOrder::info(array(
                    ['channel_code','=',$v['code']],
                    ['has_settle_account' ,'=',0],
                    ['status','=',6],
                    ['finish_datetime','between',[$start_time,$end_time]]
                ),"sum(payment_amount) as payment_amount");
                $amount = 0;
                $amount = \Common::getTicheng($payment_amount['payment_amount']??0);
                //记录提交记录
                $opera[] = DataUserTransfer::createData(array(
                    'date'  => \Tools::getDateTimeByTime(time(),'Y-m-d'),
                    'code'  =>\Common::uniqidDate(16,'W'),
                    'amount'    =>$amount*100,
                    'bank_name'=>$v['bank_name'],
                    'bank_bran'=>$v['bank_child_name'],
                    'bank_user'=>$v['invoice_name'],
                    'bank_code'=>$v['bank_code'],
                    'remark'=>input('audit_remark'),
                    'audit_remark'=>input('audit_remark'),
                    'audit_datetime'=>\Tools::getDateTimeByTime(),
                    'create_at'=>\Tools::getDateTimeByTime(),
                    'change_time'=>\Tools::getDateTimeByTime(),
                    'audit_status'=>1,
                    'channel'=>$v['channel'],
                    'channel_code'=>$v['code'],
                ));
                //标记未打款  增加结算金额
                if($amount > 0) $opera[] = DataWechat::update(array(
                    'settlement_amount' => $v['settlement_amount'] + $amount * 100,
                    'updated_at'        =>\Tools::getDateTimeByTime()
                ),array(
                    'id'    => $v['id']
                ))->save();
                //标记订单为已结算
                $opera[] = ShopOrder::update(array(
                    'has_settle_account'    => 1
                ),array(
                    ['channel_code','=',$v['code']],
                    ['has_settle_account' ,'=',0],
                    ['status','=',6],
                    ['finish_datetime','between',[$start_time,$end_time]]
                ))->save();
            }
            if(\Tools::checkArrayResult($opera)){
                $userDataWechatModel->commit();
            }else{
                $userDataWechatModel->rollBack();
                sysoplog('结算佣金失败','系统：结算佣金：失败');
                //TODO 发短信警告
            }
        } catch (\Exception $exception) {
            $this->queue->error($exception->getMessage());
        }
    }
}
